package com.ruanyun.tio.net.common.utils;


public class CrcUtils {
    /**
     * 16进制字符串计算校验和
     * @param hexStr
     * @return
     */
    public static String makeChecksum(String hexStr) {
        if (hexStr == null || hexStr.equals("")) {
            return "";
        }
        int total = 0;
        int len = hexStr.length();
        int num = 0;
        while (num < len) {
            String s = hexStr.substring(num, num + 2);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }
        /**
         * 用256求余最大是255，即16进制的FF
         */
        int mod = total % 256;
        String hex = Integer.toHexString(mod);
        len = hex.length();
        // 如果不够校验位的长度，补0,这里用的是两位校验
        if (len < 2) {
            hex = "0" + hex;
        }
        return hex;
    }
}
